using System.Collections.Generic;
using EPiServer.Core;

namespace EPiSugar.EntityAdapter.PropertyBinders
{
    public class LazyChildList<T> : IList<T> where T : class
    {
        private readonly PageReference parentLink;
        private readonly IPageSource pageSource;

        public LazyChildList(PageReference parentLink, IPageSource pageSource)
        {
            this.parentLink = parentLink;
            this.pageSource = pageSource;
        }

        private IList<T> list;
        protected IList<T> List
        {
            get
            {
                if (list == null)
                {
                    list = pageSource.GetChildren(parentLink).ToEntityList<T>();
                }
                return list;
            }
        }

        #region IList<T> Members

        public int IndexOf(T item)
        {
            return List.IndexOf(item);
        }

        public void Insert(int index, T item)
        {
            List.Insert(index, item);
        }

        public void RemoveAt(int index)
        {
            List.RemoveAt(index);
        }

        public T this[int index]
        {
            get { return List[index]; }
            set { List[index] = value; }
        }

        #endregion

        #region ICollection<T> Members

        public void Add(T item)
        {
            List.Add(item);
        }

        public void Clear()
        {
            List.Clear();
        }

        public bool Contains(T item)
        {
            return List.Contains(item);
        }

        public void CopyTo(T[] array, int arrayIndex)
        {
            List.CopyTo(array, arrayIndex);
        }

        public int Count
        {
            get { return List.Count; }
        }

        public bool IsReadOnly
        {
            get { return ((IList<T>)List).IsReadOnly; }
        }

        public bool Remove(T item)
        {
            return List.Remove(item);
        }

        #endregion

        #region IEnumerable<T> Members

        public IEnumerator<T> GetEnumerator()
        {
            return List.GetEnumerator();
        }

        #endregion

        #region IEnumerable Members

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        #endregion
    }
}